package database.example.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionFactory {
	private String driver;
	private String url;
	private String id;
	private String password;
	
	private static ConnectionFactory instance = new ConnectionFactory();
	
	public static Connection getConnection(){//외부에서는 이것만 보인다.나머지는 private라 안보임
		return instance.createConnection();
	}
	
	private ConnectionFactory(){
		loadProperties();
		
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			System.err.printf("%s", "MySQL DRIVER not found!!");
			System.exit(-1);//비정상종료
		}
	}
	
	private Connection createConnection(){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, id, password);
			System.out.println("MySQL connection success!!");
		} catch (SQLException e) {
			System.err.printf("%s", "Error : Unable connect to MySQL!!");
		}
		return conn;
	}
	private void loadProperties() {
		Properties prop = DbProperties.loadProperties("dbcon.xml");
		driver = prop.getProperty("DRIVER");
		url = prop.getProperty("URL");
		id = prop.getProperty("ID");
		password = prop.getProperty("PASSWORD");		
	}
}
